package com.qk.management.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.user.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public List<Activity> getByType(Integer type) {
        List<Activity> activities =  activityMapper.selectByType(type);
        return activities;
    }

    @Override
    public void update(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);

    }

    @Override
    public Activity getById(Integer id) {
        Activity activity =  activityMapper.selectById(id);
        return activity;
    }

    @Override
    public void add(Activity activity) {
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }

    @Override
    public void deleteById(Integer id) {

        List<Clue> clues = clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId, id));
        if (!clues.isEmpty()){
            CommonException.throwCommonException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }



        activityMapper.deleteById(id);
    }

    @Override
    public PageResult<Activity> list(ActivityDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        List<Activity>  activities = activityMapper.selectList(dto);

        Page<Activity> page = (Page<Activity>) activities;

        return PageResult.<Activity>builder().
                total(Long.valueOf(page.getTotal()).intValue()).
                rows(page.getResult())
                .build();

    }
}
